<?php
/**
 * @package  site
 */

class OrderPackageGridFieldDetailForm extends GridFieldDetailForm {
}

class OrderPackageGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest {
    private static $allowed_actions = array(
        'edit',
        'view',
        'ItemEditForm',
        'doPrint',
        'doViewPayment'
    );
    
    public function updateCMSActions() {
        $actions = FieldList::create();
		
		if($this->record->canPrint()){
			$printButton = FormAction::create('doPrint', _t('OrderPackageGridFieldDetailForm.BUTTONPRINT', 'Print'))->setAttribute('data-icon', 'grid_print')->setAttribute('data-print-link', $this->Link('doPrint'))->setUseButtonTag(true);
			$actions->push($printButton);
		}
		
		if($this->record->canApprove()){
			$approveButton = FormAction::create('doApprove', _t('OrderPackageGridFieldDetailForm.BUTTONAPPROVE', 'Approve'))->setAttribute('data-icon', 'accept')->setUseButtonTag(true);
            $actions->push($approveButton);
		}
		
		if($this->record->canVoid()){
			$voidButton = FormAction::create('doVoid', _t('OrderPackageGridFieldDetailForm.BUTTONVOID', 'Void'))->setAttribute('data-icon', 'decline')->setUseButtonTag(true);
            $actions->push($voidButton);
		}
		
		if(Permission::check('CMSACCESSPaymentAdmin') && $this->record->PaymentReceipt()->canView() && $this->record->PaymentReceipt()->exists()){
            $viewPaymentButton = FormAction::create('doViewPayment', _t('OrderPackageGridFieldDetailForm.BUTTONVIEWRECEIPT', 'View Payment Receipt'))->setAttribute('data-icon', 'navigation')->setUseButtonTag(true);
            $actions->push($viewPaymentButton);
        }
		
        return $actions;
    }

    public function ItemEditForm() {
        $form = parent::ItemEditForm();

        $form->setActions($this->updateCMSActions());
        return $form;
    }
    
    public function doPrint(){
        return $this->record->ViewPrint();
    }
	
	public function doViewPayment(){
        $link = Controller::join_links(PaymentAdmin::create()->Link(), 'Receipt', "EditForm", "field", 'Receipt', "item", $this->record->PaymentReceiptID, "edit");
        return Controller::curr()->redirect($link);
    }

	public function doApprove($data, $form) {
        $controller = $this->getToplevelController();

        try {
            DB::getConn()->transactionStart();
			$id = OrderPackage::update_status($this->record->ID, 'Fully Paid');
            DB::getConn()->transactionEnd();
			$this->record = DataObject::get_by_id($this->record->ClassName, $id);
			$this->gridField->getList()->add($this->record);
        }
        catch(ValidationException $e) {
            DB::getConn()->transactionRollback();
            $form->sessionMessage($e->getResult()->message(), 'bad');
            $responseNegotiator = new PjaxResponseNegotiator( array(
                'CurrentForm' => function() use (&$form) {
                    return $form->forTemplate();
                },
                'default' => function() use (&$controller) {
                    return $controller->redirectBack();
                }

            ));
            if($controller->getRequest()->isAjax()) {
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
            }
            return $responseNegotiator->respond($controller->getRequest());
        }

        $message = _t('OrderPackageGridFieldDetailForm.SUCCESS_APPROVED', 'Order package has been successfully approved');
        //end custom code

        $form->sessionMessage($message, 'good');

        if($this->gridField->getList()->byId($this->record->ID)) {
            // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
            // to the same URL (it assumes that its content is already current, and doesn't reload)
            return $this->edit(Controller::curr()->getRequest());
        } else {
            // Changes to the record properties might've excluded the record from
            // a filtered list, so return back to the main view if it can't be found
            $noActionURL = $controller->removeAction($data['url']);
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
            return $controller->redirect($noActionURL, 302);
        }
    }

	public function doVoid($data, $form) {
        $controller = $this->getToplevelController();

        try {
            DB::getConn()->transactionStart();
			$id = OrderPackage::update_status($this->record->ID, 'Voided');
            DB::getConn()->transactionEnd();
			$this->record = DataObject::get_by_id($this->record->ClassName, $id);
			$this->gridField->getList()->add($this->record);
        }
        catch(ValidationException $e) {
            DB::getConn()->transactionRollback();
            $form->sessionMessage($e->getResult()->message(), 'bad');
            $responseNegotiator = new PjaxResponseNegotiator( array(
                'CurrentForm' => function() use (&$form) {
                    return $form->forTemplate();
                },
                'default' => function() use (&$controller) {
                    return $controller->redirectBack();
                }

            ));
            if($controller->getRequest()->isAjax()) {
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
            }
            return $responseNegotiator->respond($controller->getRequest());
        }

        $message = _t('OrderPackageGridFieldDetailForm.SUCCESS_VOIDED', 'Order package has been successfully voided');
        //end custom code

        $form->sessionMessage($message, 'good');

        if($this->gridField->getList()->byId($this->record->ID)) {
            // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
            // to the same URL (it assumes that its content is already current, and doesn't reload)
            return $this->edit($controller->getRequest());
        } else {
            // Changes to the record properties might've excluded the record from
            // a filtered list, so return back to the main view if it can't be found
            $noActionURL = $controller->removeAction($data['url']);
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
            return $controller->redirect($noActionURL, 302);
        }
    }
}
